package ThreadTest;

import java.util.concurrent.locks.ReentrantLock;

// 主类
public class BankTest2 {
    public static void main(String[] args) {
        Account account = new Account(0);
        Man man1 = new Man(account);
        Man man2 = new Man(account);

        Thread thread = new Thread(man1);
        Thread thread1 = new Thread(man2);
        thread.setName("甲");
        thread1.setName("乙");
        thread.start();
        thread1.start();

    }
}

// 构造线程（用户），执行存钱动作
class Man implements Runnable{
    private Account act;

    public Man(Account act) {
        this.act = act;
    }
    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            act.deposit(1000);
        }
    }
}


// 构造账户，定义存钱动作
class Account{
    private int account;
    private ReentrantLock reentrantLock = new ReentrantLock();

    public Account(int account) {
        this.account = account;
    }

    public int getAccount() {
        return account;
    }

    public void deposit(int money){
        reentrantLock.lock();
        try {
            account += money;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : 账户余额：" + this.getAccount());

        }finally {
            reentrantLock.unlock();
        }
    }
}
// 构造账户，定义存钱动作
//class Account{
//    private int account = 0;
//
//    public Account(int account) {
//        this.account = account;
//    }
//
//    public int getAccount() {
//        return account;
//    }
//
//    public synchronized void deposit(int money){
//        account += money;
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(Thread.currentThread().getName() + " : 账户余额：" + this.getAccount());
//    }
//}

